package com.hcss.common.validation;

import com.hcss.common.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * @描述:
 * @作者: xuqian
 * @创建日期: 2018-10-18 11:25
 * @公司 浙江鸿程计算机系统有限公司
 */
@Slf4j
public class ByteLengthValidator implements ConstraintValidator<ByteLength, Object> {
    private int length;
    private int scale;

    @Override
    public void initialize(ByteLength byteLength) {
        this.length = byteLength.length();
        this.scale = byteLength.scale();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
        if (object == null) return true;

        String str = object.toString();
        int index = str.indexOf(CommonConstants.POINT);
	    if (index < 0) {
	        return str.getBytes( StandardCharsets.UTF_8 ).length <= length;
	    } else {
	        String precision = str.substring(0, index);
	            if (scale > 0) {
	                String decimal = str.substring(index + 1);
	                return (precision.getBytes( StandardCharsets.UTF_8 ).length <= (length - scale)) &&
	                        (decimal.getBytes( StandardCharsets.UTF_8 ).length <= scale);
	            } else {
	                return precision.getBytes( StandardCharsets.UTF_8 ).length <= length;
	            }
	    }
    }
}
